package com.jx.cashier.card.impl;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;

import com.jx.cashier.card.CardCallback;
import com.jx.cashier.card.PayDeviceType;
import com.jx.cashier.card.ReaderCard;

public class NFCReaderCardImpl implements ReaderCard {

    private Activity activity;
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private CardCallback callback;

    private long startTime = 0;
    private int timeout = 15;
    private boolean reading = false;

    @Override
    public PayDeviceType getPayDeviceType() {
        return PayDeviceType.NFC;
    }

    @Override
    public boolean init(Activity activity) {

        this.activity = activity;

        mAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (mAdapter == null) {
            return false;
        }
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        return true;
    }

    @Override
    public void setTimeOut(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public void startRead() {
        reading = true;
        startTime = System.currentTimeMillis();
    }

    @Override
    public void stopRead() {
        reading = false;
        startTime = 0;
    }

    @Override
    public void onResume() {
        mAdapter.enableForegroundDispatch(activity, mPendingIntent,
                null, null);
    }

    @Override
    public void onPause() {
        mAdapter.disableForegroundDispatch(activity);
    }

    @Override
    public void setReadCallback(CardCallback callback) {
        this.callback = callback;
    }

    @Override
    public void resolveIntent(Intent intent) {

        if (!reading) {
            return;
        }

        if (startTime == 0){
            return;
        }

        if (intent == null) {
            return;
        }

        long now = System.currentTimeMillis();
        if (((now - startTime) / 1000) > timeout) {
            return;
        }

        String action = intent.getAction();
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            String cardNo = Coverter.cardNo8To10(Coverter.getUid(intent));
            if (!cardNo.isEmpty() ) {
                reading = false;
                startTime = 0;
                if (callback != null){
                    callback.refreshCardNo(cardNo);
                }
            }
        }
    }

}
